<?php
/**
 * @title 35. 搜索插入位置 - 二分查找
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer
     */
    function searchInsert($nums, $target) {
        /**
         * @since 2020-07-17 左右指针
         */
        $left = 0;
        $right = count($nums)-1;

        /**
         * @since 2020-07-17 确定范围
         */
        if($target < $nums[$left]){
            return $left;
        } elseif($target > $nums[$right]) {
            return $right+1;
        } else {
            /**
             * @since 2020-07-17 target在left和right之间
             */
            while($left<$right){
                $mid = ($left+$right)>>1;
                $val = $nums[$mid];

                if($val == $target){
                    return $mid;
                    break;
                } elseif($val > $target) {
                    $right = $mid;
                } else {
                    $left = $mid+1;
                }
            }

            /**
             * @return
             */
            return $left;
        }
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.17.php
 */
$datas = [
    [[1,3,5,6], 5],
    [[1,3,5,6], 2],
    [[1,3,5,6], 7],
    [[1,3,5,6], 0],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->searchInsert($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
